<?php

//Modify this settings for database connection
$database_server = '';
$database_user = '';
$database_password = '';
$database_database = 'sshmein';


/********** DONT EDIT BELOW THIS LINE ***********/

function updateStamp($key){
	$now = time();
	mysql_query("update hosts set lastcheck='{$now}' where tunnel_key='{$key}'");
}

function updateLog($key, $msg){
  	mysql_query("update hosts set log='{$msg}' where tunnel_key='{$key}'");
}


//Checking if a tunnel_key was gived
if (!isset($_GET['key']) || strlen($_GET['key']) != '36'){
	exit;
}

//Connection to databases
mysql_connect($database_server, $database_user, $database_password);
mysql_select_db($database_database);

//sanitizing the tunnel key
$tunnel_key = mysql_real_escape_string($_GET['key']);

//Fetching tunnel's informations for the requested key
$query = "select * from hosts where tunnel_key='$tunnel_key'";
$res = mysql_query($query);
$row = mysql_fetch_array($res);

//Validating the remote address 
if (!empty($row['authorized_ip'])){
	$remote_address = $_SERVER['REMOTE_ADDR'];
    if ($remote_address != $row['authorized_ip']){
    	$error = "The remote IP address was \'{$remote_address}\'... didn\'t match with the authorized address";
		updateLog($tunnel_key, $error);
		updateStamp($tunnel_key);
      	exit;
    }
}

//Checking tunnel state...
if ($row['tunnel_status'] == 'ON'){
	updateStamp($tunnel_key);
	if (!empty($row['gateway_user']) && !empty($row['gateway_host']) && !empty($row['gateway_port'])){
		updateLog($tunnel_key, "The tunnel was ON... tunneling parameters has been send!");
    	echo $row['gateway_user'].":".$row['gateway_host'].":".$row['gateway_port'];
    }else{
    	$msg = "The tunnel was ON but a gateway parameter was missing";
    	updateLog($tunnel_key, $msg);
    	}
}else{
	updateLog($tunnel_key, 'The tunnel status was OFF');
	updateStamp($tunnel_key);
}

?>
